import jwt, { SignOptions } from 'jsonwebtoken';
import { JwtPayload } from '../types';

// JWT配置
export const JWT_CONFIG = {
  // JWT密钥，从环境变量获取，如果没有则使用默认值（仅用于开发）
  secret: process.env.JWT_SECRET || 'your-super-secret-jwt-key-change-in-production',
  // 访问令牌过期时间（15分钟）
  accessTokenExpiry: process.env.JWT_ACCESS_EXPIRY || '360m',
  // 刷新令牌过期时间（7天）
  refreshTokenExpiry: process.env.JWT_REFRESH_EXPIRY || '7d',
};

/**
 * 生成访问令牌
 */
export const generateAccessToken = (payload: Omit<JwtPayload, 'iat' | 'exp'>): string => {
  const options: any = {
    expiresIn: JWT_CONFIG.accessTokenExpiry,
    issuer: 'express-ts-backend',
    audience: 'client',
  };
  
  return jwt.sign(payload as object, JWT_CONFIG.secret, options);
};

/**
 * 生成刷新令牌
 */
export const generateRefreshToken = (payload: Omit<JwtPayload, 'iat' | 'exp'>): string => {
  const options: any = {
    expiresIn: JWT_CONFIG.refreshTokenExpiry,
    issuer: 'express-ts-backend',
    audience: 'refresh',
  };
  
  return jwt.sign(payload as object, JWT_CONFIG.secret, options);
};

/**
 * 验证访问令牌
 */
export const verifyAccessToken = (token: string): JwtPayload => {
  return jwt.verify(token, JWT_CONFIG.secret, {
    issuer: 'express-ts-backend',
    audience: 'client',
  }) as JwtPayload;
};

/**
 * 验证刷新令牌
 */
export const verifyRefreshToken = (token: string): JwtPayload => {
  return jwt.verify(token, JWT_CONFIG.secret, {
    issuer: 'express-ts-backend',
    audience: 'refresh',
  }) as JwtPayload;
};

/**
 * 解码token（不验证，仅用于获取payload）
 */
export const decodeToken = (token: string): JwtPayload | null => {
  try {
    return jwt.decode(token) as JwtPayload;
  } catch {
    return null;
  }
}; 